<template>
  <div class="source-button" @click="gotoSource">
    <img class="icon" src="/static/icon/source.svg" alt="" />
    <img class="arrow" src="/static/icon/right-arrow.svg" alt="" />
  </div>
  <scroll-view
    class="scroll-container"
    scroll-y="true"
    refresher-enabled="true"
    :refresher-triggered="refresherTriggered"
    @refresherrefresh="onRefresherRefresh"
    @scrolltolower="onScrollToLower"
    lower-threshold="100"
  >
    <div class="service">
      <div class="banner">
        <img class="img" src="/static/notice/banner.jpg" alt="" />
      </div>
      <div class="search">
        <div class="search-input">
          <img class="icon" src="/static/icon/search.svg" alt="" />
          <input 
            type="text" 
            placeholder="搜索通知公告名称" 
            class="name" 
            v-model="query.title"
            @confirm="handleSearch"
            confirm-type="search"
          />
          <img
            v-if="query.title"
            @click.stop="handleClearSearch"
            class="cancel"
            src="/static/icon/cancel.svg"
            alt=""
          />
        </div>
      </div>
      <div class="body">
        <div class="item" v-for="item in noticeList" :key="item.id" @click="handleOpenNotice(item)">
          <div class="time">{{ formatTime(item.publishTime) }}</div>
          <div class="flex">
            <div class="title">{{ item.title }}</div>
            <image class="cover" :src="handleProxy(item.coverImage)" mode="aspectFill" />
          </div>
        </div>
        <!-- 加载状态提示 -->
        <div class="load-more" v-if="loading && noticeList.length > 0">
          <text class="load-text">加载中...</text>
        </div>
        <div class="no-more" v-if="noMoreData && noticeList.length > 0">
          <text class="no-more-text">没有更多数据了</text>
        </div>
      </div>
    </div>
  </scroll-view>
</template>
<script setup>
wx.showShareMenu({
  withShareTicket: true,
  menus: ['shareAppMessage', 'shareTimeline'],
})
import { getNoticeList, handleProxy } from '@/api/data.js'
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
const gotoSource = () => {
  uni.redirectTo({
    url: '/pages/source/source',
  })
}
const query = ref({
  page: 1,
  pageSize: 10,
  title: '',
})
const total = ref(0)
const noticeList = ref([])
const loading = ref(false)
const refresherTriggered = ref(false)
const noMoreData = ref(false)

const fetchData = (isRefresh = false) => {
  if (loading.value) return

  loading.value = true

  getNoticeList(query.value.page, query.value.pageSize, query.value.title)
    .then((res) => {
      const newData = res.data.data.list || []
      total.value = res.data.data.total || 0

      if (isRefresh || query.value.page === 1) {
        // 刷新或首次加载，直接替换数据
        noticeList.value = newData
      } else {
        // 加载更多，追加数据
        noticeList.value = [...noticeList.value, ...newData]
      }

      // 判断是否还有更多数据
      const totalLoaded = noticeList.value.length
      noMoreData.value = totalLoaded >= total.value || newData.length < query.value.pageSize

      loading.value = false
      if (refresherTriggered.value) {
        refresherTriggered.value = false
      }
    })
    .catch((err) => {
      console.error('获取通知列表失败:', err)
      loading.value = false
      if (refresherTriggered.value) {
        refresherTriggered.value = false
      }
    })
}

// 下拉刷新
const onRefresherRefresh = () => {
  refresherTriggered.value = true
  query.value.page = 1
  noMoreData.value = false
  fetchData(true)
}

// 上拉加载更多
const onScrollToLower = () => {
  if (loading.value || noMoreData.value) return

  query.value.page += 1
  fetchData(false)
}

// 处理搜索
const handleSearch = () => {
  query.value.page = 1
  noMoreData.value = false
  fetchData(true)
}

// 清空搜索
const handleClearSearch = () => {
  query.value.title = ''
  query.value.page = 1
  noMoreData.value = false
  fetchData(true)
}

const handleOpenNotice = (item) => {
  if (item.type === 'link') {
    wx.openOfficialAccountArticle({
      url: item.linkUrl, // 此处填写公众号文章连接
      success: (res) => {},
      fail: (res) => {},
    })
  } else {
    uni.navigateTo({
      url: `/pages/notice-detail/notice-detail?id=${item.id}`,
    })
  }
}
function formatTime(dateStr) {
  // 将传入的字符串转为 Date 对象
  const inputDate = new Date(dateStr.replace(/-/g, '/'))
  if (isNaN(inputDate)) {
    return '无效时间'
  }

  // 获取当前时间
  const now = new Date()

  // 计算时间差（毫秒）
  const diffMs = now - inputDate
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))

  // 1. 小于一天 → “今天”
  if (diffDays < 1) {
    return '今天'
  }
  // 2. 大于等于一天，小于两天 → “昨天”
  else if (diffDays < 2) {
    return '昨天'
  }
  // 3. 小于7天 → 返回星期几
  else if (diffDays < 7) {
    const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
    const dayOfWeek = inputDate.getDay() // 0=星期日, 1=星期一, ..., 6=星期六
    return weekdays[dayOfWeek]
  }
  // 4. 超过或等于7天 → 返回“M月D日”格式
  else {
    const year = inputDate.getFullYear()
    const month = inputDate.getMonth() + 1 // getMonth() 是 0-11
    const day = inputDate.getDate()
    return `${year}年${month}月${day}日`
  }
}
onLoad((e) => {
  fetchData()
})
</script>

<style lang="scss">
.search {
  margin-top: 20rpx;
  width: 750rpx;
  height: 88rpx;
  padding: 8rpx 24rpx;

  .search-input {
    width: 702rpx;
    height: 72rpx;
    border-radius: 44rpx;
    background: #fff;
    display: flex;
    align-items: center;
    gap: 20rpx;
    padding: 16rpx 24rpx;

    .icon {
      width: 40rpx;
      height: 40rpx;
    }

    .name {
      flex: 1;
      font-family: PingFang SC;
      font-weight: 400;
      font-style: Regular;
      font-size: 28rpx;
      &::placeholder {
        color: #999;
      }
    }

    .cancel {
      margin-left: 12px;
      width: 16px;
      height: 16px;
      margin-bottom: 2px;
      margin-right: 5px;
    }
  }
}
.scroll-container {
  height: calc(100vh - 100rpx); // 减去 source-button 的高度
  width: 100%;
}

.service {
  .banner {
    width: 750rpx;
    height: 240rpx;
    padding-left: 6%;
    padding-right: 6%;
    margin-top: 16rpx;
    .img {
      border-radius: 24rpx;
    }
  }
  .body {
    padding: 20rpx 24rpx;
    display: flex;
    flex-direction: column;
    gap: 32rpx;
    .item {
      width: 100%;
      border-radius: 24rpx;
      background: #fff;
      padding: 24rpx;
      display: flex;
      flex-direction: column;
      gap: 16rpx;
      .flex {
        display: flex;
        gap: 16rpx;
      }
      .title {
        font-family: PingFang SC;
        font-weight: 500;
        font-style: Medium;
        font-size: 30rpx;
        letter-spacing: 0px;
        flex: 1;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
        height: fit-content;
      }
      .cover {
        width: 150rpx;
        height: 120rpx;
        border-radius: 8rpx;
        flex-shrink: 0;
      }
      .time {
        color: #ccc;
        font-family: PingFang SC;
        font-weight: 500;
        font-style: Medium;
        font-size: 28rpx;
        letter-spacing: 0px;
      }
    }

    .load-more,
    .no-more {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 32rpx 0;

      .load-text,
      .no-more-text {
        font-size: 28rpx;
        color: #999;
        font-family: PingFang SC;
      }
    }
  }
}
</style>
